package com.example.food_contract_system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.food_contract_system.domain.Region;
import com.example.food_contract_system.domain.SysRegion;
import com.example.food_contract_system.mapper.SysRegionMapper;
import com.example.food_contract_system.service.RegionService;
import com.example.food_contract_system.mapper.RegionMapper;
import com.example.food_contract_system.util.R;
import com.example.food_contract_system.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Lhy
* @description 针对表【region】的数据库操作Service实现
* @createDate 2023-07-06 09:22:19
*/
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService{

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private SysRegionMapper sysRegionMapper;

    @Override
    public R getRegion() {
        //查出所有数据
        List<SysRegion> parent = sysRegionMapper.selectList(null);

        //组成树形结构
        List<RegionVo> regionVos = parent.stream().filter(p ->
                p.getRegionParentId().equals("-1")
        ).map(p -> {
            //获取子列表
            RegionVo regionVo = new RegionVo();
            regionVo.setValue(p.getRegionId());
            regionVo.setLabel(p.getRegionName());

            regionVo.setChildren(getChildren(p, parent));
            return regionVo;
        }).collect(Collectors.toList());

        if (regionVos.size() > 0){
            return R.ok().put("data",regionVos);
        }

        return R.error(500,"没有数据");
    }

    private List<RegionVo> getChildren(SysRegion p, List<SysRegion> parent) {
        List<RegionVo> regionVos = parent.stream().filter(parents -> {
            return parents.getRegionParentId().equals(p.getRegionId());
        }).map(parents -> {
            RegionVo regionVo = new RegionVo();
            regionVo.setValue(parents.getRegionId());
            regionVo.setLabel(parents.getRegionName());
            regionVo.setChildren(getChildren(parents, parent));

            return regionVo;
        }).collect(Collectors.toList());
        return regionVos;
    }

}




